const Koa = require('koa')
const multer = require('koa-multer')
const Router = require('koa-router')
const views = require('koa-views')
const compose = require('koa-compose')

const path = require('path')
const app = new Koa()

// Must be used before any router is used
app.use(views(path.join(__dirname, 'views'), {
    map: { html: 'nunjucks' } //需要安装nunjucks包
}))

const router = new Router()

//http://www.zengqs.com/
router.get('/', async (ctx, next) => {
    await ctx.render('multer', {
        title: 'Hello koa2'
    })
})

//文件上传
//配置
const storage = multer.diskStorage({
    //文件保存路径
    destination: function (req, file, cb) {
        cb(null, 'public/uploads/')
    },
    //修改文件名称
    filename: function (req, file, cb) {
        var fileFormat = (file.originalname).split(".");  //以点分割成数组，数组的最后一项就是后缀名
        cb(null, Date.now() + "." + fileFormat[fileFormat.length - 1]);
    }
})

//加载配置
const upload = multer({ storage: storage });
//路由
//POST http://www.zengqs.com/upload
router.post('/upload', upload.single('file'), async (ctx, next) => {
    ctx.body = {
        filename: ctx.req.file.filename,//返回文件名
        data: ctx.req.file
    }
})

//组合多个中间件，中间件执行区分顺序
// const all = compose([router.routes(), router.allowedMethods()]);
// app.use(all);
app.use(router.routes());
app.use(router.allowedMethods())

app.listen(3000, () => {
    console.log('server is running at http://localhost:3000')
});